package com.xhs.config;

import com.mongodb.client.MongoClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;

import javax.annotation.Resource;

/**
 * @desc: MongoDB多数据源配置
 * @projectName: springboot-mongodb
 * @author: xhs
 * @date: 2023-11-16 016 22:02
 * @version: JDK 1.8
 */
@Configuration
public class MongoConfig {

    @Resource
    private MongoClient mongoClient;
    @Resource
    private MongoProperties mongoProperties;

//    /**
//     * MONGODB事务配置
//     *
//     * @param factory factory
//     * @return MongoTransactionManager
//     */
//    @Bean
//    MongoTransactionManager mongoTransactionManager(MongoDatabaseFactory factory) {
//        return new MongoTransactionManager(factory);
//    }

    /**
     * 默认的数据库
     *
     * @return MongoTemplate
     */
    @Bean
    public MongoTemplate mongoTemplate() {
        return new MongoTemplate(mongoClient, mongoProperties.getDatabase());
    }

    /**
     * 第二个数据源
     *
     * @param adminUri uri
     * @return MongoTemplate
     */
    @Bean
    public MongoTemplate mongoTemplateLowCode(@Value("${spring.data.mongodb.low-code.uri}") String adminUri) {
        return new MongoTemplate(new SimpleMongoClientDatabaseFactory(adminUri));
    }

    /**
     * 第三个数据源
     *
     * @param adminUri uri
     * @return MongoTemplate
     */
    @Bean
    public MongoTemplate mongoTemplateEvent(@Value("${spring.data.mongodb.event.uri}") String adminUri) {
        return new MongoTemplate(new SimpleMongoClientDatabaseFactory(adminUri));
    }
//    @Bean
//    MessageListenerContainer messageListenerContainer(MongoTemplate template, DocumentListener documentListener) {
//
//        Executor executor = Executors.newSingleThreadExecutor();
//        MessageListenerContainer messageListenerContainer = new DefaultMessageListenerContainer(template, executor) {
//            @Override
//            public boolean isAutoStartup() {
//                return true;
//            }
//        };
//        ChangeStreamRequest request = ChangeStreamRequest.builder()
//                //需要监听的集合名，不指定默认监听数据库的
//                .collection("topic")
//                //过滤需要监听的操作类型，可以根据需求指定过滤条件
//                .filter(newAggregation(match(where("operationType").in("insert", "update", "replace"))))
//                //不设置时，文档更新时，只会发送变更字段的信息，设置UPDATE_LOOKUP会返回文档的全部信息
//                .fullDocumentLookup(FullDocument.UPDATE_LOOKUP)
//                .build();
//        messageListenerContainer.register(request, Document.class);
//        return messageListenerContainer;
//    }
}
